package com.xzx.shop_front_api.schedule;

import com.google.gson.Gson;
import com.xzx.shop_front_api.entity.Messages;
import com.xzx.shop_front_api.service.MessageService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MessageTask {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MessageService messageService;

    @Value("${rabbitmq.queue.name}")
    private String queueName;

    // 修改定时任务方法
    @Scheduled(cron = "0 30 2 * * ?")
    public void consumeFromRabbitMqPeriodically() {
        System.out.println("定时任务开始从 RabbitMQ 获取消息: " + dateFormat.format(new Date()));

        Object receivedMessage = rabbitTemplate.receive(queueName); // 主动获取一条消息

        if (receivedMessage != null) {
            try {
                // 1. 从 Message 对象中获取消息体（byte[]）
                byte[] messageBodyBytes = ((org.springframework.amqp.core.Message) receivedMessage).getBody();

                // 2. 将 byte[] 转换为字符串
                String messageBody = new String(messageBodyBytes, StandardCharsets.UTF_8);

                System.out.println("从队列接收到消息: " + messageBody);
                Gson gson = new Gson();
                // 后续的 JSON 解析等逻辑...
                Messages objMessage = gson.fromJson(messageBody, Messages.class);
                messageService.insertMessage(objMessage);
                System.out.println("消息处理成功。");

            } catch (Exception e) {
                System.err.println("处理消息时发生异常: " + e.getMessage());
                e.printStackTrace(); // 打印完整的异常堆栈，便于排查

            }
        } else {
            System.out.println("队列中没有新消息。");
        }

        System.out.println("定时任务执行完毕。");
    }
}